<template>
    <div className="graph-io">
        <span title="下载 XML" @click="downloadXml">
            <img src="https://cdn.jsdelivr.net/gh/Logic-Flow/static@latest/docs/examples/case/bussiness/bpmn/download.png"
                alt="下载XML" />
        </span>
        <span id="upload-xml" title="上传 XML">
            <input type="file" className="upload" @change="uploadXml($event)" />
            <img className="upload-img"
                src="https://cdn.jsdelivr.net/gh/Logic-Flow/static@latest/docs/examples/case/bussiness/bpmn/upload.png"
                alt="上传XML" />
        </span>
    </div>
</template>

<script setup lang="ts">
import type LogicFlow from '@logicflow/core';


const { lf } = defineProps<{ lf: LogicFlow }>()

const downloadXml = () => {
    const data = lf.getGraphData() as string;
    download('logic-flow.xml', data);
};

const download = (filename: string, text: string) => {
    const element = document.createElement('a');
    element.setAttribute(
        'href',
        'data:text/plain;charset=utf-8,' + encodeURIComponent(text),
    );
    element.setAttribute('download', filename);
    element.style.display = 'none';
    document.body.appendChild(element);
    element.click();
    document.body.removeChild(element);
};

const uploadXml = (ev: any) => {
    const file = ev.target.files[0];
    const reader = new FileReader();
    reader.onload = (event: ProgressEvent<FileReader>) => {
        if (event.target) {
            const xml = event.target.result as any;
            lf.render(xml);
        }
    };
    reader.readAsText(file);
};

</script>


<style lang="less" scoped>
.graph-io {
    position: absolute;
    left: 10px;
    bottom: 10px;
    z-index: 9999;
    background: rgba(255, 255, 255, 0.8);
    box-shadow: 0 1px 4px rgba(0, 0, 0, .3);
    padding: 10px;
    display: flex;
}

.graph-io>span {
    margin: 0 5px;
    cursor: pointer;
}

#upload-xml {
    position: relative;
    overflow: hidden;
    display: inline-block;
    cursor: pointer;
}

.upload {
    position: absolute;
    z-index: 99;
    left: 0;
    top: 0;
    opacity: 0;
    cursor: pointer;
}

.upload::-webkit-file-upload-button {
    cursor: pointer;
}

.upload-img {
    width: 26px;
}
</style>